#include "Polynomial.h"

void InitPolynomial(Polynomial p) {
    p->next = NULL;
    p->xishu = 0;
    p->zhishu = 0;
}

int GetLength(Polynomial p) {
    int len = 0;
    if (p) {
        Polynomial temp = p;
        while (p->next) {
            p = p->next;
            len++;
        }
    }
    return len;
}

void AddNode(Polynomial p, int xishu, int zhishu) {
    if (p) {
        //按照指数从小到大的顺序找到插入点
        int index = 0;
        int i = -1;
        Polynomial temp = p;
        while (temp->next) {
            temp = temp->next;
            i++;
            if (zhishu < temp->zhishu)
                break;
            else if (zhishu == temp->zhishu)
                p->xishu += xishu;
            else
                index = i + 1;
        }

        //在指定位置插入数据
        temp = p;
        for (int i = 0; i < index; i++)
            temp = temp->next;

        Polynomial temp2 = temp->next;
        pNode newNode = (pNode)malloc(sizeof(Node));
        newNode->next = temp2;
        newNode->xishu = xishu;
        newNode->zhishu = zhishu;

        temp->next = newNode;
    }
}

void ClearPolynomial(Polynomial p) {
    while (p->next) {
        Polynomial removedNode = p->next;
        p->next = removedNode->next;
        free(removedNode);
    }
}

long getValue(const Polynomial p, int x) {
    //应该采用迭代相乘进行计算，而不是机械地每个节点值相加
    return 0;
}

//将p2多项式增加至p1
void AddPolynomial(const Polynomial p1, const Polynomial p2) {
    if (p1 && p2) {
        Polynomial temp = p2;
        while (temp->next) {
            temp = temp->next;
            AddNode(p1, temp->xishu, temp->zhishu);
        }
    }
}

void PrintPolynomial(const Polynomial p) {
    Polynomial temp = p;
    while (temp->next) {
        temp = temp->next;
        printf("%dx^%d + ", temp->xishu, temp->zhishu);
    }
}

void TestPolynomial() {
    //在堆上分配内存病初始化
    Polynomial p1 = (Polynomial)malloc(sizeof(Node));
    Polynomial p2 = (Polynomial)malloc(sizeof(Node));
    InitPolynomial(p1);
    InitPolynomial(p2);

    AddNode(p1, 1, 0);
    AddNode(p1, 3, 10000);
    AddNode(p1, 2, 20000);
    printf("\np1:len=%d\n", GetLength(p1));
    PrintPolynomial(p1);

    AddNode(p2, 1234, 50);
    printf("\np2:len=%d\n", GetLength(p2));
    PrintPolynomial(p2);

    AddPolynomial(p1, p2);
    printf("\np1+p2:len=%d\n", GetLength(p1));
    PrintPolynomial(p1);

    //释放头结点和元素的内存
    ClearPolynomial(p1);
    free(p1);
    ClearPolynomial(p2);
    free(p2);
}